/**
 * Created by MorenYang on 2017/11/12.
 */
import axios from 'axios';
import {authStore} from '../index'
import qs from 'qs'

const r = axios.create();
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

if (process.env.NODE_ENV === 'development') {
  r.defaults.baseURL = 'http://172.17.12.40:8080/admin';
} else {
  r.defaults.baseURL = '/admin'
}

r.defaults.headers.post['Content-Type'] = 'application/json';
r.defaults.cancelToken = source.token;

r.interceptors.request.use(
  config => {
    const authState = authStore.getState().auth;
    if (!!authState.token) {
      config.headers['token'] = authState.token;
    } else {
      source.cancel('No Permission');
    }
    return config;
  },
  error => Promise.reject(error)
);

export const get = (url, payload) => {
  if (payload) {
    url = `${url}?${qs.stringify(payload)}`
  }
  return r.get(url).then(({data}) => data);
};

export const post = (url, payload) => {
  if (!payload) payload = {};
  return r.post(url, payload).then(({data}) => data);
};

export default {
  get,
  post,
  r
}
